﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.ProductionPlans;
using Reporting.Domain;
using Reporting.Domain.Enum;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.ProductionPlans;

namespace Reporting.API.Application.CommandHandler.ProductionPlans
{
    public class DeleteProductionPlanCommandHandler : IRequestHandler<DelProductionPlanCommand, ApiResult>
    {
        private readonly IProductionPlanRepository _productionPlanRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<DeleteProductionPlanCommandHandler> _logger;

        public DeleteProductionPlanCommandHandler(ILogger<DeleteProductionPlanCommandHandler> logger, IMapper mapper, IProductionPlanRepository productionPlanRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionPlanRepository = productionPlanRepository;
        }
        public async Task<ApiResult> Handle(DelProductionPlanCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产计划
                var productionPlans = await _productionPlanRepository.GetAsync(x => x.Productionplanid == request.Productionplanid);
                if (productionPlans == null)
                {
                    return ApiResult.Fail("删除失败，当前数据不存在",StatusCodeEnum.BadRequest);
                }
                // 删除生产计划
               var result = await _productionPlanRepository.DeleteAsync(productionPlans);
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除失败");
                throw;
            }
        }
    }
}
